package com.rayo.accesscontrollercopy.model.biz;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.config.OfficeModeConfig;
import com.rayo.accesscontrollercopy.model.callback.OnGetDbListener;
import com.rayo.accesscontrollercopy.model.callback.OnUpdateDbListener;
import com.rayo.accesscontrollercopy.model.db.bean.DmuTimeData;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.bean.SystemData;
import com.rayo.accesscontrollercopy.model.db.dao.CalendarImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CardTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.CardUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.DSTImpl;
import com.rayo.accesscontrollercopy.model.db.dao.DmuTimeDao;
import com.rayo.accesscontrollercopy.model.db.dao.DmuTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.HeartImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataImp;
import com.rayo.accesscontrollercopy.model.db.dao.KeyTimeImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.LockImp;
import com.rayo.accesscontrollercopy.model.db.dao.OperatorImpl;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyAddImpl;
import com.rayo.accesscontrollercopy.model.db.dao.PlanKeyTempImpl;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.model.db.dao.SystemDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.SystemDataImpl;
import com.rayo.accesscontrollercopy.utils.AppUtils;
import com.rayo.accesscontrollercopy.utils.TimeFormatUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;


/**
 * Created by yanghaojie on 16/7/26.
 */
public class ParamBiz implements IParamBiz {
    private SystemDataDao systemDataDao = new SystemDataImpl();

    @Override
    public void init(OnGetDbListener onGetDbListener) {
        if (null != GlobalVariables.getInstance().getmSystemData()) {
            onGetDbListener.onSuccess(GlobalVariables.getInstance().getmSystemData());
        } else {
            SystemData systemData = systemDataDao.findFirst();
            if (null == systemData) {
                systemData = new SystemData();
                systemDataDao.addSystem(systemData);
            }
            GlobalVariables.getInstance().setmSystemData(systemData);
            onGetDbListener.onSuccess(systemData);
        }

    }

    @Override
    public void saveParam(SystemData systemData, OnUpdateDbListener onUpdateDbListener) {
        systemDataDao.updateSystem(systemData);
        GlobalVariables.getInstance().setmSystemData(systemData);
        onUpdateDbListener.onSuccess("param", systemData);
    }

    @Override
    public String getVersion(Context context) {
        StringBuilder sb = new StringBuilder(64);
        sb.append(AppUtils.getVersion(context));
        sb.append("\n");
        if (GlobalVariables.getInstance().getmSiteData().getName()!=null){
            sb.append("Name:"+GlobalVariables.getInstance().getmSiteData().getName());
        }
        sb.append("\n");
        sb.append("Ip:"+getIPAddress(context));
        sb.append("\n");
        sb.append("MAC:"+GlobalVariables.getInstance().getAndroidId());
        return sb.toString();
    }
    public  String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public  String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    @Override
    public String getOfficeMode(Context context) {
        SiteDao siteDao = new SiteImpl();
        DmuTimeDao dmuTimeDao = new DmuTimeImpl();
        SiteData siteData = siteDao.findFirst();
        StringBuilder sb = new StringBuilder(64);
        if (null == siteData) {
            sb.append(context.getString(R.string.setting_no_office_mode));
        } else {
            switch (siteData.getMode()) {
                case OfficeModeConfig.STANDAR_MODE:
                    sb.append(context.getString(R.string.setting_standard_mode));
                    break;
                case OfficeModeConfig.OFFICE_MODE:
                    sb.append(context.getString(R.string.setting_office_mode));
                    break;
                case OfficeModeConfig.ON_OFF_MODE:
                    sb.append(context.getString(R.string.setting_on_off_mode));
                    break;
                case OfficeModeConfig.TIME_ON_OFF_MODE:
                    sb.append(context.getString(R.string.setting_time_on_off_mode));
                    break;
                default:
                    sb.append(context.getString(R.string.setting_no_office_mode));
                    break;
            }
            sb.append("\n");
            List<DmuTimeData> dmuTimeDatas = dmuTimeDao.findAll();
            int pos = 1;
            for (DmuTimeData dmuTimeData : dmuTimeDatas) {
                sb.append(String.valueOf(pos) + ". ");
                sb.append(TimeFormatUtil.dateToTime(dmuTimeData.getFrom()));
                sb.append(" - ");
                sb.append(TimeFormatUtil.dateToTime(dmuTimeData.getTo()));
                sb.append("  ");
                if (dmuTimeData.getSun() == 1) sb.append(context.getString(R.string.sunday) + ", ");
                if (dmuTimeData.getMon() == 1) sb.append(context.getString(R.string.monday) + ", ");
                if (dmuTimeData.getTue() == 1)
                    sb.append(context.getString(R.string.tuesday) + ", ");
                if (dmuTimeData.getWed() == 1)
                    sb.append(context.getString(R.string.wednesday) + ", ");
                if (dmuTimeData.getThu() == 1)
                    sb.append(context.getString(R.string.thursday) + ", ");
                if (dmuTimeData.getFri() == 1) sb.append(context.getString(R.string.friday) + ", ");
                if (dmuTimeData.getSat() == 1)
                    sb.append(context.getString(R.string.saturday) + ", ");
                sb.append("\n");
                pos++;
            }
        }
        return sb.toString();
    }

    @Override
    public void getNetworkInfo(OnGetDbListener onGetDbListener) {
        if (null != GlobalVariables.getInstance().getmSystemData()) {
            onGetDbListener.onSuccess(GlobalVariables.getInstance().getmSystemData());
        } else {
            SystemData systemData = systemDataDao.findFirst();
            if (null == systemData) {
                systemData = new SystemData();
                systemDataDao.addSystem(systemData);
            }
            GlobalVariables.getInstance().setmSystemData(systemData);
            onGetDbListener.onSuccess(systemData);
        }
    }

    @Override
    public void saveNetworkInfo(String ip, String port, OnUpdateDbListener onUpdateDbListener) {
        SystemData systemData = GlobalVariables.getInstance().getmSystemData();
        systemData.setServerIp(ip);
        systemData.setServerPort(port);
        systemDataDao.updateSystem(systemData);
        GlobalVariables.getInstance().setmSystemData(systemData);
        onUpdateDbListener.onSuccess(OnUpdateDbListener.ACTION_DB_SUCCESS, systemData);
    }

    @Override
    public void cleanCache(OnUpdateDbListener onUpdateDbListener) {
        new CalendarImpl().deleteAll();
        new CardTimeImpl().deleteAll();
        new CardUserImpl().deleteAll();
        new DSTImpl().delete();
        new HeartImpl().deleteAll();
        new KeyTimeImpl().deleteAll();
        new KeyUserImpl().deleteAll();
        new OperatorImpl().deleteAll();
        new PlanKeyAddImpl().deleteAll();
//        new PlanKeyDelImpl().deleteAll();
        new PlanKeyTempImpl().deleteAll();
        new KeyDataImp().deleteAll();
        new LockImp().deleteAll();
        onUpdateDbListener.onSuccess(OnUpdateDbListener.ACTION_DB_SUCCESS, null);
    }
}
